package com.zhang.es;

import com.google.gson.Gson;
import com.zhang.model.User;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.fetch.subphase.highlight.Highlighter;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Map;

/**
 * @program: elasitcsearch
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-03-10
 **/

//192.168.117.128  9301
public class Fuxiday2 {
    private TransportClient client;

    @Before
    public void setClient() throws Exception {
        Settings settings = Settings.builder()
            .put("cluster.name", "my-elasticsearch")
            .build();
        client = new PreBuiltTransportClient(settings)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.117.128"), 9301))
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.117.130"), 9302));
    }
    @Test
    public void createIndex(){
        client.admin().indices().prepareCreate("java2").get();
        client.close();
    }

    @Test
    public void putMapping() throws IOException {
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder
            .startObject()
                .startObject("user")
                    .startObject("properties")
                        .startObject("id")
                            .field("type","long")
                            .field("index",true)
                            .field("store",true)
                        .endObject()
                        .startObject("userName")
                            .field("type","text")
                            .field("index",true)
                            .field("analyzer","ik_smart")
                        .endObject()
                    .endObject()
                .endObject()
            .endObject();
        client.admin().indices().preparePutMapping("java2").setType("user").setSource(builder).get();
        client.close();
    }
    @Test
    public void delIndex(){
        client.admin().indices().prepareDelete("java2").get();
        client.close();
    }
    @Test
    public void addUser(){
        for (int i = 0; i < 50; i++) {
            User user = new User();
            user.setId(i);
            user.setUserName("人生如一面镜子，你对它笑，它也对你笑，你对它哭，它也对你哭。下一秒会发生什么是一个难解的谜题，但我们可以选择怎样去面对。笑着过也是一天，哭着过也是一天。何不开开心心地度过每一天?\n" +
                "\n" +
                "人生虽苦，但我心有乐。\n" +
                "\n" +
                "一屋，一人，没有高谈阔论的声音，也没有嘻哈打闹的热闹场面。心里也许会升起一股孤独凄清之感，升腾起些许凉意。但配上一壶热腾腾地普洱茶，一本钟爱的传记，再加上一张可以自动伸缩，温暖舒适的躺椅，准备妥当后，接着拉开已挂了一晚上，把黑暗带来的窗帘，霎时一阵刺眼的阳光从远方照来，全身暖洋洋的，清风拂面，伴着余烟袅袅的热茶，好不惬意。\n" +
                "\n" +
                "我们都知道“高处不胜寒”，自古以来，身居高位，尤其是历届帝皇，拥有无上的权柄，却少了些许寻常人的欢乐，宛若一人身处高楼。+"+i+"+");
            Gson gson = new Gson();
            String s = gson.toJson(user);
            client.prepareIndex()
                  .setIndex("java2")
                  .setType("user")
                  .setSource(s)
                .get();
        }
        client.close();
    }
    @Test
    public void delDoc(){
        client.prepareDelete()
                .setIndex("java2")
                .setType("user")
                .setId("AXDJp4dxIUqhYw-zAwWE").get();
        client.close();
    }
    @Test
    public void upDoc(){
        User user = new User();
        user.setId(123);
        user.setUserName("斯大林快放假啦的时间法拉第");
        Gson gson = new Gson();
        String s = gson.toJson(user);
        client.prepareUpdate()
                .setIndex("java2")
                .setType("user")
                .setDoc(s)
                .setId("AXDJp4nYIUqhYw-zAwWK")
                .get();
        client.close();;
    }
    @Test
    public void getById(){
        QueryBuilder builder = QueryBuilders.idsQuery().addIds("AXDJp4oOIUqhYw-zAwWM");
        SearchResponse searchResponse = client.prepareSearch("java2").setTypes("user").setQuery(builder).get();
        SearchHits searchHits = searchResponse.getHits();
        System.out.println(searchHits.getTotalHits()+"总条数");
        SearchHit[] searchHit = searchHits.getHits();
        for (SearchHit searchHitFields : searchHit) {
            Map<String, Object> source = searchHitFields.getSource();
            System.out.println(source.get("userName"));
        }
    }

    @Test
    public void getByQuery(){
        QueryBuilder builder = QueryBuilders.boolQuery().must(QueryBuilders.queryStringQuery("人生如一面镜子").defaultField("userName"));
        SearchResponse searchResponse = client.prepareSearch("java2")
            .setTypes("user")
            .setQuery(builder)
            .get();
        SearchHits searchHits = searchResponse.getHits();
        System.out.println(searchHits.getTotalHits());
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> source = searchHit.getSource();
            System.out.println(source.get("userName"));
        }
    }
    @Test
    public void high(){
        QueryBuilder builder = QueryBuilders.boolQuery().must(QueryBuilders.queryStringQuery("人生如一面镜子").defaultField("userName"));

        HighlightBuilder highlightBuilder = new HighlightBuilder().field("userName").preTags("<span>").postTags("</span>");

        SearchResponse searchResponse = client.prepareSearch("java2").setTypes("user").setQuery(builder).highlighter(highlightBuilder).get();

        SearchHits searchHits = searchResponse.getHits();

        for (SearchHit searchHit : searchHits) {
            Map<String, Object> source = searchHit.getSource();
            Object userName = source.get("userName");
            System.out.println(userName);
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            HighlightField userName1 = highlightFields.get("userName");
            Text[] fragments = userName1.fragments();
            for (Text fragment : fragments) {
                System.out.println(fragment);
            }
        }
    }
}
